package com.fanketly.funacg2.ui.components

import android.util.Log
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DismissDirection
import androidx.compose.material3.DismissState
import androidx.compose.material3.DismissValue
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SwipeToDismiss
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDismissState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.fanketly.funacg2.R
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.ui.theme.Brown
import com.fanketly.funacg2.ui.theme.FunACG2Theme
import com.fanketly.funacg2.ui.theme.WhiteText200
import com.fanketly.funacg2.ui.theme.dp4
import com.fanketly.funacg2.ui.theme.dp6
import com.fanketly.funacg2.ui.theme.dp8

@OptIn(
    ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class
)
@Composable
fun HomeListCard(work: WorkList.Work, onTagClick: (tag: Int) -> Unit, onClick: () -> Unit) {
    ElevatedCard(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth(0.9f)
            .padding(top = dp8, bottom = dp8),
    ) {
        Column {
            Box {
                AsyncImage(
                    model = work.thumbnailCoverUrl,
                    contentDescription = null,
                    modifier = Modifier.fillMaxWidth(),
                    placeholder = painterResource(id = R.drawable.ic_launcher_background),
                    contentScale = ContentScale.FillWidth
                )
                Text(
                    text = "RJ${work.id}",
                    modifier = Modifier
                        .padding(8.dp)
                        .background(Brown, MaterialTheme.shapes.extraSmall)
                        .padding(4.dp),
                    style = MaterialTheme.typography.bodySmall,
                    color = WhiteText200,
                )
                Text(
                    text = work.release,//发布日期 createDate是上传日期
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .background(
                            color = MaterialTheme.colorScheme.background.copy(alpha = 0.7f),
                            shape = RoundedCornerShape(topStart = 8.dp),
                        )
                        .padding(4.dp),
//                    fontWeight = FontWeight.Bold,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onBackground,
                )
            }
            Column(
                modifier = Modifier.padding(horizontal = dp8, vertical = dp4),
            ) {
                Text(
                    text = work.title,
                    color = MaterialTheme.colorScheme.onSurface,
                    style = MaterialTheme.typography.titleLarge,
                )
                Text(
                    text = "${work.name}(CV:${work.vas.getOrNull(0)?.name})",
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier
                        .padding(top = dp8)
                        .alpha(0.5f)
                )
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = dp8, bottom = dp8),
                    verticalAlignment = Alignment.CenterVertically,
//                    horizontalArrangement = Arrangement.End
                ) {
                    RatingBar(
                        rating = work.rateAverage2dp.toFloat(), modifier = Modifier.height(26.dp)
                    )
                    Text(
                        text = work.rateAverage2dp.toString(),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(start = dp4)
                    )
                    Text(
                        text = "(${work.rateCount})",
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        style = MaterialTheme.typography.bodyMedium
                    )
//                    Text(
//                        text = "销量:1000", maxLines = 1,
//                        textAlign = TextAlign.End,
//                        modifier = Modifier.weight(1f),
//                        overflow = TextOverflow.Ellipsis,
////                        color = MaterialTheme.colorScheme.onSurfaceVariant,
//                        style = MaterialTheme.typography.bodyMedium
//                    )
                }
                FlowRow(Modifier.fillMaxWidth()) {
                    work.tags.forEach {
                        OutlinedText(
                            text = it.name,
                            padding = dp6,
                            modifier = Modifier
                                .padding(dp4)
                                .clickable {
                                    onTagClick(it.id)
                                },
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SwipeToDelete(
    modifier: Modifier = Modifier,
    title: String,
    thumbnailCoverUrl: String,
    dismissedToEnd: () -> Unit,
    onDelete: () -> Unit,
    onClick: () -> Unit,
) {
    var currentProgress by remember {
        mutableFloatStateOf(0f)
    }
    val dismissState = rememberDismissState(confirmValueChange = {
        Log.d(TAG, "confirmValueChange: $it,$currentProgress")
        if (it == DismissValue.DismissedToStart) {
            if (currentProgress >= 0.5f && currentProgress < 1) {
                onDelete()
                return@rememberDismissState true
            }
        }
        true
    }, positionalThreshold = {
        it / 2
    })
    ForUpdateData {/*缩小重组范围，减少重组*/
        currentProgress = dismissState.progress
//                Log.i(
//                    TAG,
//                    "ForUpdateData: " + currentProgress + "," + dismissState.currentValue + "," + dismissState.targetValue
//                )
    }
    SwipeToDismiss(state = dismissState,
        modifier = modifier
            .padding(4.dp)
            .fillMaxWidth(),
        directions = setOf(DismissDirection.EndToStart),
        background = {
            SwipeToDeleteBackground(dismissState = dismissState, dismissedToEnd)
        }, dismissContent = {
            Card(
                elevation = CardDefaults.cardElevation(4.dp),
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable(onClick = onClick)
            ) {
                Row {
                    AsyncImage(
                        model = thumbnailCoverUrl,
                        contentDescription = null,
                        modifier = Modifier
                            .padding(8.dp)
                            .width(100.dp),
                        placeholder = painterResource(id = R.drawable.ic_launcher_background),
                        contentScale = ContentScale.FillWidth
                    )
                    Text(
                        text = title,
                        modifier = Modifier.padding(8.dp),
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 3
                    )
                }
            }
        })
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SwipeToDeleteBackground(
    dismissState: DismissState,
    dismissedToEnd: () -> Unit,
) {
    LaunchedEffect(key1 = dismissState.dismissDirection, block = {
        if (dismissState.dismissDirection == DismissDirection.StartToEnd) {
            dismissedToEnd()
        }
    })
    val color by animateColorAsState(
        when (dismissState.targetValue) {
            DismissValue.Default -> MaterialTheme.colorScheme.surface
            DismissValue.DismissedToEnd -> Color.Green
            DismissValue.DismissedToStart -> Color.Red
        }, label = ""
    )
    val scale by animateFloatAsState(
        if (dismissState.targetValue == DismissValue.Default) 0.75f else 1f, label = ""
    )
    Box(
        Modifier
            .fillMaxSize()
            .background(color)
            .padding(horizontal = 20.dp),
        contentAlignment = Alignment.CenterEnd
    ) {
        Icon(
            Icons.Default.Delete,
            contentDescription = "Localized description",
            modifier = Modifier.scale(scale)
        )
    }
}

@Composable
private fun ForUpdateData(onUpdate: () -> Unit) {
    onUpdate()
}

@Preview
@Composable
private fun CardPreview() {
    FunACG2Theme {
        Column {
            repeat(4) {
                SwipeToDelete(
                    modifier = Modifier.height(50.dp),
                    title = "1",
                    thumbnailCoverUrl = "1",
                    dismissedToEnd = {},
                    onDelete = { }) {
                }
            }
        }
    }
}
